/******************************************************************
Copyright © PsuCtl 2017~2024. All rights reserved.
* @projectName   PsuCtl
* @author        Raiiwhen
* @email         masterraii@icloud.com
*******************************************************************/

// IN180-A2 IDVBR 50x
// Res 10mR
// Gain = 0.5R

#include <stdio.h>
#include "esp_console.h"
#include "esp_log.h"
#include "ads128d818.h"

static i2c_master_dev_handle_t g_ads;
static const char* TAG = "ADS";

void AdsRegWrite8Bit(uint8_t reg, uint8_t val);
uint8_t AdsRegRead8Bit(uint8_t reg);

void AdsConfig(uint8_t devAddr, i2c_master_bus_handle_t bus, uint32_t freq)
{
    printf("AdsConfig Addr[0x%02x] bus[0x%08lx] freq[%lu]\n", devAddr, (uint32_t)bus, freq);
    i2c_device_config_t chip = {
        .scl_speed_hz = freq,
        .device_address = devAddr,
    };
    int ret = i2c_master_bus_add_device(bus, &chip, &g_ads);
    printf("ads add device [0x%02x] %s with 0x%x\n", devAddr, ret == ESP_OK ? "success" : "failed", ret);
    AdsRegWrite8Bit(0x0, 0x1); // start chip
    AdsRegWrite8Bit(0xb, 0x2); // select mode 1, 8 channel in used; select 2.56V internal Vref
    uint8_t mfrID = AdsRegRead8Bit(0x3e); // Manufacturer ID
    uint8_t revID = AdsRegRead8Bit(0x3f); // Revision ID
    printf("ads mfrID[0x%02x] revID[0x%02x]\n", mfrID, revID);
}

void AdsRegRead16Bit(uint8_t reg, uint16_t* val)
{
    uint8_t data[2] = {0};
    int ret = i2c_master_transmit_receive(g_ads, &reg, sizeof(reg), data, sizeof(data), 50);
    *val = data[0] << 8 | data[1];
    ESP_LOGD(TAG, "RegRead16Bit %s : reg[0x%02x] data[0x%04x]\n", ret == ESP_OK ? "success" : "failed", reg, *val);
}

uint8_t AdsRegRead8Bit(uint8_t reg)
{
    uint8_t val = 0;
    int ret = i2c_master_transmit_receive(g_ads, &reg, sizeof(reg), &val, sizeof(val), 50);
    ESP_LOGD(TAG, "AdsRegRead8Bit %s : reg[0x%02x] data[0x%04x]\n", ret == ESP_OK ? "success" : "failed", reg, val);
    return val;
}

void AdsRegWrite8Bit(uint8_t reg, uint8_t val)
{
    uint8_t data[2] = {reg, val};
    int ret = i2c_master_transmit(g_ads, data, sizeof(data), 50);
    ESP_LOGD(TAG, "RegWrite8Bit %s : reg[0x%02x] data[0x%04x]\n", ret == ESP_OK ? "success" : "failed", reg, val);
}

void AdsReadVoltage(float val[8])
{
    for (int ch = 0; ch < 8; ch++) {
        uint16_t regVal = 0;
        AdsRegRead16Bit(0x20 + ch, &regVal);
        val[ch] = (float)(regVal >> 4) / 4096.0f * 2.56f; // internal Vref = 2.56V
    }
}